export interface TreeItem {
  id: number;
  parentId: number;
  children?: TreeItem[];
  isFolder: boolean;
  [key: string]: any;
}
/**
 * 将数组转换为树形结构
 * @param data 数组
 * @param sortType 排序方式，默认为asc，可选值：asc、desc
 */
export function buildTree(rawData: TreeItem[], sortType: string = 'asc') {
  const tree = [];
  const nodesMap = new Map();
  const data = rawData.sort((a, b) => {
    if (sortType === 'asc') {
      return a.sort - b.sort;
    } else {
      return b.sort - a.sort;
    }
  });
  // 先将所有节点存入Map以便快速查找
  data.forEach((node) => {
    const { id, isFolder, path } = node;
    nodesMap.set(id, { ...node, key: id });
  });

  // 遍历节点，构建树结构
  data.forEach((node) => {
    const { parentId } = node;
    if (parentId === 0) {
      // 根节点直接添加到树中
      tree.push(nodesMap.get(node.id));
    } else {
      // 非根节点，添加到对应的父节点的children数组中
      const parentNode = nodesMap.get(parentId);
      if (parentNode) {
        if (!parentNode.children) {
          parentNode.children = [];
        }
        parentNode.children.push(nodesMap.get(node.id));
      }
    }
  });

  return tree;
}
